<template>
  <div id="LabInstrSetup">
    <Breadcrumb content="检验仪器" />
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="检验仪器">
          <Splitpanes class="area">
            <Pane size="55">
              <vxe-toolbar perfect>
                <template #buttons>
                  <span class="smallToolTitle">检验组:</span>
                  <vxe-select v-model="form.workGroup" filterable clearable @change="findInstrSetupPageList" placeholder="请选择检验组">
                    <vxe-option value="" label="全部"></vxe-option>
                    <vxe-option v-for="workGroup in workGroupList" :key="workGroup.commonId" :label="workGroup.name" :value="workGroup.code"></vxe-option>
                  </vxe-select>
                  <span class="smallToolTitle">仪器大类:</span>
                  <vxe-select v-model="form.instrClass" filterable clearable @change="findInstrSetupPageList" placeholder="请选择检验组">
                    <vxe-option value="" label="全部"></vxe-option>
                    <vxe-option v-for="workGroup in instrClassList" :key="workGroup.commonId" :label="workGroup.name" :value="workGroup.code"></vxe-option>
                  </vxe-select>

                  <span class="smallToolTitle">仪器名称:</span>
                  <vxe-input v-model="form.instrName" placeholder="仪器名称" class="vxeInputSearch" type="text" clearable @clear="findInstrSetupPageList"></vxe-input>

                  <vxe-button type="text" icon="vxe-icon-search" class="button-blue SearchBtn" content="查询" :loading="loading" @click="findInstrSetupPageList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
                  <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="loading1" @click="pullPloyee"></vxe-button> -->
                </template>
              </vxe-toolbar>

              <div class="tableBox">
                <vxe-table ref="labInstrSetupTable" :border="'inner'" align="left" class="mytable-scrollbar" height="auto" :loading="loading" :data="instrSetupList" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: true
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source @current-change="roleRowClick">
                  <vxe-column type="checkbox" width="30px"></vxe-column>
                  <vxe-column type="seq" width="30"></vxe-column>
                  <vxe-column field="instrCode" title="仪器代号"> </vxe-column>
                  <vxe-column field="instrName" title="仪器名称"> </vxe-column>
                  <vxe-column field="instrCalled" title="仪器简介"> </vxe-column>
                  <vxe-column field="instrMark" title="仪器型号"> </vxe-column>
                  <vxe-column field="instrClass" title="仪器类别">
                    <template #default="{ row }">
                      <span>{{ formatCommon(instrClassList, row.instrClass) }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="instrRegister" title="仪器注册码"> </vxe-column>
                  <vxe-column field="isQc" title="是否质控" width="80">
                    <template #default="{ row }">
                      <vxe-checkbox v-model="row.isQc"></vxe-checkbox>
                    </template>
                  </vxe-column>
                </vxe-table>

                <!-- <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                    'PrevJump',
                    'PrevPage',
                    'Number',
                    'NextPage',
                    'NextJump',
                    'Sizes',
                    'FullJump',
                    'Total'
                  ]" @page-change="handleSizeChange($event)">
                </vxe-pager> -->
              </div>
            </Pane>
            <Pane size="45">
              <!-- 检验仪器基本信息表单 -->
              <LabInstrSetupFormPoct ref="refFormData" @getTableData="findInstrSetupPageList" />
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/lis/instrSetup"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { pageSizes, formatDateTime } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '@/stores/store';
import XEUtils from 'xe-utils';
import { VXETable } from 'vxe-table';
import { VxeNotifyType, VxeMessage } from '@/utils/CommonMessage';
import LabInstrSetupFormPoct from './LabInstrSetupFormPoct.vue'; //检验仪器基本信息表单
import LogInfo from '@/components/LogInfo.vue'; //日志

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let workGroupList: any = reactive([]); //检验组option
let instrClassList: any = reactive([]);

let form = reactive({
  instrName: '', //仪器名称
  workGroup: '', //检验组
  instrClass: '', //仪器大类
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
});

let labInstrSetupTable = ref(); //检验仪器表格标记ref
let instrSetupList: any = reactive([]); //检验仪器表格数据

let loading = ref(false); //查询按钮加载
let loading1 = ref(false); //查询按钮加载
let saveLoading = ref(false);

let refFormData: any = ref(null); //检验仪器基本信息表单ref

// 方法定义区 =============

// 页面加载时
onMounted(() => {
  getDictItemsList(); //获取检验组option下拉数据
  findInstrSetupPageList(); //获取检验仪器表格数据
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['JYGZZ', 'YQDL'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const JYGZZType = dictTreeTypeItems.data.find((item) => item.code === 'JYGZZ');
  workGroupList.push(...JYGZZType.detailDataList);
  const YQDLType = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassList.push(...YQDLType.detailDataList);
}

// 获取检验仪器表格数据
function findInstrSetupPageList() {
  loading.value = true;
  instrSetupList.length = 0;
  const url = '/lis/instrSetup/findInstrSetupList';
  proxy.$http
    .get(url, {
      params: {
        instrClass: form.instrClass,
        instrName: form.instrName,
        workGroup: form.workGroup,
        orgId: form.orgId,
        poct: 1
      }
    })
    .then((res: any) => {
      instrSetupList.push(...res.data);
      roleRowClick({
        row: instrSetupList[0],
        rowIndex: 0
      });
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索仪器列表异常', VxeNotifyType.error);
    });
}

//删除按钮
function handleDelete() {
  const selectRows = (proxy.$refs.labInstrSetupTable as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的仪器', VxeNotifyType.warning);
    return;
  } else {
    proxy
      .$confirm('您确定要删除当前选中的这条数据吗?', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const commaSeparatedIds = selectRows.map((row) => row.id);
        const commaSeparatedNames = selectRows.map((row) => row.instrName);
        const ids = commaSeparatedIds.join(',');
        const names = commaSeparatedNames.join(',');
        const data = { ids: ids, names: names };
        const url = '/lis/instrSetup/deleteInstrSetup';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findInstrSetupPageList(); // 获取检验仪器表格数据
            refFormData.value.clearFormData(); //调用子组件的清空表单方法
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      });
  }
}

// 点击表格当前行
function roleRowClick({ row, rowIndex }: any) {
  // obj:any
  // console.log('------------------row', obj.row);
  // refFormData.value.initPage(obj.row); //传递给右侧基本信息表单
  refFormData.value.initPage(row); //传递给右侧基本信息表单
  (proxy.$refs.labInstrSetupTable as any).setCurrentRow(row);
}

//下拉选择之后触发保存当前
function selectchange(e: any) {
  e.aimKeys.forEach((item: any) => {
    if (e.isChild) {
      instrSetupList[e.childIndex][item.targetField] = e.row[item.sourceField];
      if (item.targetField === 'reportUnitEntity') {
        instrSetupList[e.childIndex].groupNo = e.row[item.sourceField].id;
      }
    } else {
      //表单用
    }
  });
}

// 点击修改新增保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = labInstrSetupTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords();

    // 拿到列表中id为空的为新增
    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let data = e;

      proxy.$http
        .post('/lis/instrSetup/edit', data)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/lis/instrSetup/addInstrSetup', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findInstrSetupPageList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

//这个月第一天日期
function getThisMonthFirstDay() {
  let today = new Date();
  today.setDate(1);
  today.setHours(0, 0, 0, 0);
  return today;
}
//当前日期
function getThisMonthNewDay() {
  let today = new Date();
  return today;
}

function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss.SSS'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}

// 同步数据
async function pullPloyee() {
  loading1.value = true;
  const url = '/lis/instrSetup/syncInstrs';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/lisInterface/lisInterfacePost',
    code: 'GET_EMPLOYEE'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      loading1.value = false;
      findInstrSetupPageList();
    })
    .catch((err: any) => {
      loading1.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#LabInstrSetup {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    .el-tabs {
      height: 100%;
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;
        #pane-0,
        #pane-1 {
          height: 100%;
        }
      }
    }
    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: calc(100% - 32px);

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
}
</style>
